package com.hu.ta.assignment5.util;

/**
 * 
 */

import java.util.Properties;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;

/**
 * Interface for the command line.
 * 
 * @author cage@g.com
 */
public class CommandLineReader {

	private CommandLine cmdLine;

	private Options options;

	public CommandLineReader(final String[] args) {
		createCommandLineOptions();
		parseCommandLine(args);
	}

	private void createCommandLineOptions() {
		options = new Options();

		for (CommandLineProperties configEnum : CommandLineProperties.values()) {
			if (null != configEnum.getOption()) {
				options.addOption(configEnum.getOption());
			}
		}
	}

	public void parseCommandLine(final String[] agrs) {
		try {
			CommandLineParser parser = new BasicParser();
			cmdLine = parser.parse(options, agrs);
			if (cmdLine.hasOption(CommandLineProperties.HELP.getOptionKey())) {
				printHelp();
				System.exit(0);
			}
			if (cmdLine.getOptions().length != 3) {
				printError("missing or to many operands");
				System.exit(1);
			}
		} catch (Exception pe) {
			printError("wrong arguments");
			System.exit(1);
		}
	}

	private void printError(String message) {
		System.out.println(String.format("Assignment5: %s\n", message));
		printHelp();
	}

	private void printHelp() {
		HelpFormatter format = new HelpFormatter();
		format.printHelp(
				"java -jar <jar-archive Assignment5> -i <input folder> [-o <output folder>] -d <train.dat> [-l]",
				"All files are necessary.\n", options, "");
	}

	/**
	 * Load the configuration from the command line.
	 */
	public void loadConfigProperties() {

		Properties properties = ConfigurationUtils.getInstance().configurationSettings;

		for (CommandLineProperties configProperty : CommandLineProperties
				.values()) {
			if (configProperty.isLoadableByOption()) {
				if (configProperty.isOption()
						&& cmdLine.hasOption(configProperty.getOptionKey())) {
					properties.setProperty(configProperty.getConfigKey()
							.getConfigProperty(), "true");
				} else {
					properties.setProperty(configProperty.getConfigKey()
							.getConfigProperty(), cmdLine.getOptionValue(
							configProperty.getLongOptionKey(), configProperty
									.getConfigKey().getDefaultValue()));
				}
			}
		}
	}
}
